package com.group02.community.config;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.DateTimeFormatProperty;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class EasyExcelLocalDateConverter implements Converter<LocalDateTime> {

    // 默认解析格式
    private static final DateTimeFormatter DEFAULT_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return LocalDateTime.parse(cellData.getStringValue(), DEFAULT_FORMAT);
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new WriteCellData<>(value.format(getDateTimeFormat(contentProperty)));
    }

    /**
     * 获取日期转换格式
     *
     * @param contentProperty contentProperty
     * @return 日期转换格式
     */
    private DateTimeFormatter getDateTimeFormat(ExcelContentProperty contentProperty) {
        // 这个会获取定义的类的字段上有没有DateTime的注解,有的话根据这个注解定义的格式解析,没有则是使用默认的
        DateTimeFormatProperty dateTimeFormatProperty = contentProperty.getDateTimeFormatProperty();
        String format = dateTimeFormatProperty == null ? null : dateTimeFormatProperty.getFormat();
        return StringUtils.isBlank(format) ? DEFAULT_FORMAT : DateTimeFormatter.ofPattern(format);
    }
}